package com.xsz.config;

import com.xsz.entity.Administrator;
import com.xsz.service.AdministratorService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;


public class ShiroRealm extends AuthorizingRealm {
    @Resource
    private AdministratorService administratorService;

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String administratorName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        System.out.println("用户" + administratorName + "认证-----ShiroRealm.doGetAuthenticationInfo");
        Administrator administrator = administratorService.getByName(administratorName);

        if (administrator == null) {
            throw new UnknownAccountException("用户名不存在！");
        }

        //加密方式;
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                administrator, //用户名
                administrator.getPwd(), //密码
                ByteSource.Util.bytes(administrator.getCredentialsSalt()),//salt=administratorname+salt
                getName() //realm name
        );
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
